//整合函数：登录校验
checkLogin()
//渲染用户名
renderUsername()
//退出登录
registerLogout()

//获取数据
async function getData(){
    const res = await axios.get('/students')
    //渲染数据
    const html = res.data.map(v=>{
        const {name ,age, gender, group,hope_salary,salary,province ,city ,area,id} = v
        return `
         <tr>
            <td>${name}</td>
            <td>${age}</td>
            <td>${gender ===0?'男':'女'}</td>
            <td>第${group}组</td>
            <td>${hope_salary}</td>
            <td>${salary}</td>
            <td>${province + city + area}</td>
            <td data-id="${id}">
            <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
            <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
            </td>
        </tr>
        `
    }).join('')
    document.querySelector('.list').innerHTML = html
    document.querySelector('.total').innerHTML = res.data.length
}   
getData()
//显示弹窗
const modalDom = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalDom)
document.querySelector('#openModal').addEventListener('click',()=>{
    document.querySelector('.modal-title').innerHTML = '添加学员'
    //删除自定义属性
    modalDom.dataset.id = ''
    //清空籍贯
    citySelect.innerHTML = `<option value="">--城市--</option>`
    
    areaSelect.innerHTML = `<option value="">--地区--</option>`
    modal.show()
})
//省市区联动
const proSelect = document.querySelector('[name=province]')
const citySelect = document.querySelector('[name=city]')
const areaSelect = document.querySelector('[name=area]')
//获取省份
async function initSelect(){
    const proRes = await axios.get('/api/province')
    // console.log(proRes);
    const proHtml = proRes.list.map(v=> {
        return `<option value="${v}">--${v}--</option>`
    }).join('')
    proSelect.innerHTML = `<option value="">--省份--</option>${proHtml}`
    //获取城市数据+渲染
    proSelect.addEventListener('change',async ()=>{
        const cityRes = await axios({
            url:'/api/city',
            params:{
                pname:proSelect.value
            }
        })
        const cityHtml = cityRes.list.map(v=>{
            return `<option value="${v}">--${v}--</option>`
        }).join('')
        citySelect.innerHTML = `<option value="">--城市--</option>${cityHtml}`
        areaSelect.value = '<option value="">--地区--</option>'
    })
    //获取地区数据+渲染
    citySelect.addEventListener('change',async ()=>{
        const areaRes = await axios({
            url:'/api/area',
            params:{
                pname:proSelect.value,
                cname:citySelect.value
            }
        })
        const areaHtml = areaRes.list.map(v=>{
            return `<option value="${v}">--${v}--</option>`
        }).join('')
        areaSelect.innerHTML = `<option value="">--地区--</option>${areaHtml}`
    })
}
initSelect()
//数据新增
document.querySelector('#submit').addEventListener('click',()=>{
    if(modalDom.dataset.id){
        saveEdit()
    }else{
        addStudent()
    }
})
async function addStudent(){
    const form = document.querySelector('#form')
    const data = serialize(form,{hash:true,empty:true})
    // console.log(data);
    //根据接口数据类型进行转换
    data.age = +data.age
    data.gender = +data.gender
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    data.group = +data.group
    //调用接口
    try{
        const res = await axios.post('/students',data)
        //提示用户
        showToast(res.message)
        getData()
    }catch(error){
        showToast(error.response.data.message)
    }
    modal.hide()
    //数据清空
    form.reset()
   
}
//删除数据
//绑定事件
document.querySelector('.list').addEventListener('click',(e)=>{
    if(e.target.classList.contains('bi-trash')){
        const id = e.target.parentNode.parentNode.dataset.id
        delStudent(id)
    }
    if(e.target.classList.contains('bi-pen')){
        const id = e.target.parentNode.parentNode.dataset.id
        editStudent(id)

    }
})
//删除数据
async function delStudent(id){
    // console.log(id);
    await axios.delete(`/students/${id}`)
    //重新渲染
    getData()
}
//编辑数据
async function editStudent(id){
    const res = await axios.get(`/students/${id}`)
    // console.log(res);
    document.querySelector('.modal-title').innerHTML = '修改学员'
    const keyArr = ['name','group','age','hope_salary','salary']
    keyArr.forEach(key=>{
        document.querySelector(`[name=${key}]`).value = res.data[key]
    })
    //用变量控制是哪一个被选
    const {gender} = res.data
    const chks = document.querySelectorAll('[name=gender]')
    chks[gender].checked = true
    //设置籍贯
    const {province, city ,area} = res.data
    //设置省
    proSelect.value = province
    // 设置市
    const cityRes = await axios.get('/api/city',{
        params:{
            pname:province
        }
    })
    const cityHtml = cityRes.list.map(v=>{
        return `<option value="${v}">${v}</option>`
    }).join('')
    citySelect.innerHTML = `<option value="">--城市--</option>${cityHtml}`
    citySelect.value = city
    // 设置区
    const areaRes = await axios.get('/api/area',{
        params:{
            pname:province,
            cname:city
        }
    })
    const areaHtml = areaRes.list.map(v=>{
        return `<option value="${v}">${v}</option>`
    }).join('')
    areaSelect.innerHTML = areaHtml
    areaSelect.value = area
    modal.show()

    //保存学员id，用来区分 新增（dataset.id不存在）和修改（dataset.id存在）
    modalDom.dataset.id = id
}
//保存修改
async function saveEdit(){
    // console.log('baocun');
    // 收集+转换数据+提交
    const form = document.querySelector('#form')
    const data = serialize(form,{hash:true,empty:true})
    console.log(data);
    data.age = +data.age
    data.gender = +data.gender
    data.group = +data.group
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    try{
        const saveRes = await axios.put(`/students/${modalDom.dataset.id}`,data)
        showToast(saveRes.message)
    }catch(error){
        showToast(error.response.data.message)
        // console.dir(error);
    }
    modal.hide()
}